import React, { Component } from 'react'

class Child extends Component {
  render() {
    return (
      <div>
        <h2>子组件</h2>
      </div>
    )
  }
}

const Fnc = () => {
  return (
    <div>
      <h2>函数组件</h2>
    </div>
  )
}

class Index extends Component {
  state = {
    val: '',
  }

  // 1. 创建ref对象
  inputRef = React.createRef()

  comInstance = React.createRef()

  pub = (e) => {
    console.log(e)
    // 阻止表单默认行为
    e.preventDefault()
    console.log('获取表单元素输入的值：', this.state.val)
    console.log('获取对应ref对象绑定的元素：', this.inputRef.current.value)
    console.log('获取子组件的实例：', this.comInstance)
    this.inputRef.current.style.backgroundColor = 'red'
  }

  handlerInput = (e) => {
    // console.log(e.target.value)
    this.setState({
      val: e.target.value,
    })
  }

  render() {
    return (
      <div>
        <h1>表单处理</h1>
        <Child ref={this.comInstance} />
        {/* 函数组件不能绑定ref，因为它没有组件实例 */}
        {/* <Fnc ref={this.comInstance} /> */}
        <form>
          <p>{this.state.val}</p>
          <p>
            <input ref={this.inputRef} type="text" />
          </p>
          <p>
            <input
              value={this.state.val}
              onChange={this.handlerInput}
              type="text"
            />
          </p>
          <button onClick={this.pub}>提交</button>
        </form>
      </div>
    )
  }
}

export default Index
